﻿using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using T.FAS.Runtime.Base.Common;

namespace T.FAS.Runtime.Base.SGPlugin
{
    // 组件运行时服务
    public class FasComponentSGService
    {
        /// <summary>
        /// 创建多维表格
        /// </summary>
        /// <param name="filter">数据库连接key，表格编号和名称</param>
        /// <returns>多维表格id</returns>
        public Dictionary<string, string> CreateMultiDimensionTable(string filter) {
            try {
                LogUtil.Log($"CreateMultiDimensionTable-filter:{filter}");
                if (string.IsNullOrEmpty(filter))
                {
                    return new Dictionary<string, string>() { { "state","0"}, { "errmsg", "入参不能为空" } };
                }
                Dictionary<string, string> filterDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(filter);
                string tableCode = "";
                string tableName = "";
                string connectionString = "";
                filterDic.TryGetValue("docCode", out tableCode);
                filterDic.TryGetValue("docName", out tableName);
                filterDic.TryGetValue("connectionString", out connectionString);
                if(string.IsNullOrEmpty(connectionString) || string.IsNullOrEmpty(tableCode))
                {
                    return new Dictionary<string, string>() { { "state", "0" }, { "errmsg", "参数不能为空" } };
                }
                Dictionary<string, object> formData = new Dictionary<string, object>();
                formData.Add("name", tableName);
                formData.Add("dbTableName", tableCode);
                formData.Add("description", tableName);
                formData.Add("fields", new List<object>());
                formData.Add("views", new List<object>());
                formData.Add("records", new List<object>());
                formData.Add("order", 0);
                formData.Add("fieldKeyType", "id");
                formData.Add("icon", "📈");
                formData.Add("connectionString", connectionString);
                formData["fields"] = InitFormDataColumns();
                var result = PostTeable(formData);
                LogUtil.Log($"CreateMultiDimensionTable-result2:{JsonConvert.SerializeObject(result)}");
                return result;
            }catch(Exception ex)
            {
                LogUtil.Log($"CreateMultiDimensionTable-exception:{JsonConvert.SerializeObject(ex)}");
                return new Dictionary<string, string>() { { "state", "0" },{ "errmsg", ex.InnerException.ToString()} };
            }
        }

        public Dictionary<string, string> ChangeMultiDimensionTableName(string filter) {
            try
            {
                LogUtil.Log($"ChangeMultiDimensionTableName-filter:{filter}");
                if (string.IsNullOrEmpty(filter))
                {
                    return new Dictionary<string, string>() { { "state", "0" }, { "errmsg", "入参不能为空" } };
                }
                Dictionary<string, string> filterDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(filter);
                string tableId = "";
                string newName = "";
                filterDic.TryGetValue("tableid", out tableId);
                filterDic.TryGetValue("newname", out newName);
                if (string.IsNullOrEmpty(tableId) || string.IsNullOrEmpty(newName))
                {
                    return new Dictionary<string, string>() { { "state", "0" }, { "errmsg", "参数不能为空" } };
                }
                Dictionary<string, object> formData = new Dictionary<string, object>();
                
                var result = ChangeTeableName(tableId,newName);
                LogUtil.Log($"ChangeMultiDimensionTableName-result2:{JsonConvert.SerializeObject(result)}");
                return result;
            }
            catch (Exception ex)
            {
                LogUtil.Log($"ChangeMultiDimensionTableName-exception:{JsonConvert.SerializeObject(ex)}");
                return new Dictionary<string, string>() { { "state", "0" }, { "errmsg", ex.InnerException.ToString() } };
            }
        }

        #region 私有方法
        private Dictionary<string, string> PostTeable(Dictionary<string, object> formData)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            string teableUrl = string.Empty;
            string authorization = string.Empty;
            string fasTeableConfig = ConfigUtil.Instance.FasTeableConfig;// 开通端口ACL
            LogUtil.Log($"CreateMultiDimensionTable-config:{fasTeableConfig}");
            if (string.IsNullOrEmpty(fasTeableConfig) == false)
            {
                Dictionary<string, string> configDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(fasTeableConfig);
                teableUrl = configDic["TeableUrl"];
                authorization = configDic["TeableAuthorization"];
            }
            
            using (var httpClient = new HttpClient())
            {
                if (string.IsNullOrEmpty(teableUrl) == false && string.IsNullOrEmpty(authorization) == false)
                {
                    string url = $"{teableUrl}/api/base/public/table/";
                    // 添加 Authorization 头，示例为 Bearer 令牌
                    httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authorization);
                    httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                    HttpContent content = new StringContent(JsonConvert.SerializeObject(formData), Encoding.UTF8, "application/json");
                    using (var response = httpClient.PostAsync(url, content).Result)
                    {
                        response.EnsureSuccessStatusCode();
                        var result = response.Content.ReadAsStringAsync().Result;
                        LogUtil.Log($"CreateMultiDimensionTable-result:{result}");
                        Dictionary<string, object> resultDic = JsonConvert.DeserializeObject<Dictionary<string, object>>(result);
                        try
                        {
                            // Todo，失败处理
                            // 临时处理
                            dic["tableid"] = (string)resultDic["id"];
                            JArray views = (JArray)resultDic["views"];
                            dic["viewid"] = (string)views[0]["id"];
                            dic["state"] = "1";
                        }
                        catch (Exception ex)
                        {
                            LogUtil.Log($"ChangeTeableName-exception1:{ex.ToString()}");
                            dic["state"] = "0";
                            dic["errmsg"] = ex.Message;
                        }
                    }
                }

            }
            return dic;
        }

        private Dictionary<string, string> ChangeTeableName(string tableId, string newName)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            string teableUrl = string.Empty;
            string authorization = string.Empty;
            string fasTeableConfig = ConfigUtil.Instance.FasTeableConfig;// 开通端口ACL
            LogUtil.Log($"CreateMultiDimensionTable-config:{fasTeableConfig}");
            if (string.IsNullOrEmpty(fasTeableConfig) == false)
            {
                Dictionary<string, string> configDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(fasTeableConfig);
                teableUrl = configDic["TeableUrl"];
                authorization = configDic["TeableAuthorization"];
            }
            Dictionary<string, string> formData = new Dictionary<string, string>() {
                {"name", newName }
            };
            using (var httpClient = new HttpClient())
            {
                if (string.IsNullOrEmpty(teableUrl) == false && string.IsNullOrEmpty(authorization) == false)
                {
                    string url = $"{teableUrl}/api/base/public/table/{tableId}/name";
                    // 添加 Authorization 头，示例为 Bearer 令牌
                    httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authorization);
                    httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                    HttpContent content = new StringContent(JsonConvert.SerializeObject(formData), Encoding.UTF8, "application/json");
                    using (var response = httpClient.PutAsync(url, content).Result)
                    {
                        try
                        {
                            response.EnsureSuccessStatusCode();
                            var result = response.Content.ReadAsStringAsync().Result;
                            LogUtil.Log($"ChangeTeableName-result:{result}");
                        
                            dic["state"] = "1";
                        }
                        catch (Exception ex)
                        {
                            LogUtil.Log($"ChangeTeableName-exception1:{ex.ToString()}");
                            dic["state"] = "0";
                            dic["errmsg"] = ex.Message;
                        }
                    }
                }

            }
            return dic;
        }
        private List<Dictionary<string, object>> InitFormDataColumns()
        {
            var result = new List<Dictionary<string, object>>();
            //result.Add(GetField("id", "主键ID", new Tuple<string, string, string>("singleLineText", "string", "TEXT"), true));
            result.Add(GetField("code", "编号", new Tuple<string, string, string>("singleLineText", "string", "VARCHAR")));
            result.Add(GetField("name", "名称", new Tuple<string, string, string>("singleLineText", "string", "TEXT")));
            //result.Add(GetField("creator", "创建人", new Tuple<string, string, string>("singleLineText", "string", "TEXT")));
            result.Add(GetField("creatorname", "创建人姓名", new Tuple<string, string, string>("singleLineText", "string", "TEXT")));
            //result.Add(GetField("createtime", "创建时间", new Tuple<string, string, string>("date", "string", "DATE")));
            //result.Add(GetField("lastmodifier", "最后修改人", new Tuple<string, string, string>("singleLineText", "string", "TEXT"), false, false));
            result.Add(GetField("lastmodifiername", "最后修改人姓名", new Tuple<string, string, string>("singleLineText", "string", "TEXT"), false, true, false));
            //result.Add(GetField("lastmodifytime", "最后修改时间", new Tuple<string, string, string>("date", "string", "DATE"), false, true, false));
            return result;
        }
        private Dictionary<string, object> GetField(string fieldName, string displayName, Tuple<string, string, string> teableType, bool isPrimary = false, bool recordRead = true, bool recordCreate = true)
        {
            return new Dictionary<string, object> {
                                { "name", displayName },
                                { "type", teableType.Item1 },
                                { "description", "" },
                                { "isLookup", false },
                                { "notNull", isPrimary },
                                { "unique", isPrimary },
                                { "isPrimary", isPrimary },
                                { "isComputed", false },
                                { "isPending", false },
                                { "hasError", false },
                                { "cellValueType",  teableType.Item2 },
                                { "isMultipleCellValue", false},
                                { "dbFieldType",  teableType.Item3 },
                                { "dbFieldName", fieldName },
                                { "recordRead", recordRead },
                                { "recordCreate", recordCreate }
                            };
        }
        #endregion

    }
}
